package tdt4240.iddqd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.anddev.andengine.entity.sprite.AnimatedSprite;

import android.content.res.AssetManager;
import android.util.Log;

public class FileMapFactory extends MapFactory {

	private AssetManager assetManager;

	public FileMapFactory(AssetManager assets) {
		super(1, 0);
		assetManager = assets;
	}

	/**
	 * Gets a map instance, read from assets, based on the current level ID and the current checkpoint ID
	 */
	public Map getCurrentMap() {
		try {
			InputStream is = assetManager.open(Constants.DIRECTORY_LEVELS + File.separator + Constants.PREFIX_LEVELS + currentLevelId);
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line;

			List<AnimatedSprite> list = new ArrayList<AnimatedSprite>();

			while((line = br.readLine()) != null) {
				AnimatedSprite element = parseLine(line);
				if(element != null) {
					list.add(element);
				}
			}

			return createMapFromSprites(list);
		} 
		catch (FileNotFoundException e) {
			Log.v("MapParser", "Level file not found.");
			e.printStackTrace();
		} catch (IOException e) {
			Log.v("MapParser", "Error when reading line from file.");
			e.printStackTrace();
		}

		return null;
	}
}
